package com.seezoon.admin.framework.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageSerializable;
import com.seezoon.admin.framework.service.IBaseService;
import com.seezoon.dao.framework.BaseMapper;
import com.seezoon.dao.framework.entity.AbstractQueryCondition;
import org.springframework.util.Assert;

import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

/**
 * @author 黎小荣
 * @since 2023/3/22
 */
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements IBaseService<T> {

    @Override
    public T find(Serializable id) {
        return baseMapper.selectById(id);
    }

    @Override
    public T findOne(AbstractQueryCondition condition) {
        List<T> ts = this.find(condition);
        Assert.isTrue(ts.size() <= 1,
                "Expected one result (or null) to be returned by findOne(), but found: " + ts.size());
        return ts.isEmpty() ? null : ts.get(0);
    }

    @Override
    public List<T> find(AbstractQueryCondition condition) {
        return baseMapper.selectByCondition(new Page<>(1, -1), condition).getRecords();
    }

    @Override
    public PageInfo<T> find(AbstractQueryCondition condition, int pageNum, int pageSize, boolean count) {
        IPage<T> page = baseMapper.selectByCondition(new Page<>(pageNum, pageSize), condition);
        PageInfo<T> pageInfo = new PageInfo<>(page.getRecords());
        pageInfo.setTotal(page.getTotal());
        pageInfo.setSize((int) page.getCurrent());
        pageInfo.setPageSize((int) page.getSize());
        return pageInfo;
    }

    @Override
    public PageSerializable<T> find(AbstractQueryCondition condition, int pageNum, int pageSize) {
        return find(condition, pageNum, pageSize, true);
    }

    @Override
    public int saveOne(T record) {
        return baseMapper.insert(record);
    }

    @Override
    public int save(@NotEmpty T... records) {
        boolean success = saveBatch(Arrays.asList(records));
        return success ? records.length : 0;
    }

    @Override
    public int updateSelective(T record) {
        return baseMapper.updateById(record);
    }

    @Override
    public int update(T record) {
        return baseMapper.updateById(record);
    }

    @Override
    public int delete(@NotEmpty Serializable... ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }
}
